﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

using Microsoft.Win32;
using System.Net;
using com.crawler.components;
using com.crawler.common;
using System.Threading;
using System.Diagnostics;



namespace com.crawler.winfrom
{
    public partial class FrmMain : Form
    {
        private System.Diagnostics.PerformanceCounter m_cpu_counter;
        private System.Diagnostics.PerformanceCounter m_memory_counter;
        private CrawlerManager m_crawler_mgr = null;

        public FrmMain()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
            this.m_cpu_counter = new System.Diagnostics.PerformanceCounter();
            this.m_memory_counter = new System.Diagnostics.PerformanceCounter("Memory", "Available MBytes");

            this.m_cpu_counter.CategoryName = "Processor";
            this.m_cpu_counter.CounterName = "% Processor Time";
            this.m_cpu_counter.InstanceName = "_Total"; 
        }

        private int m_cpu_usage;
        /// <summary>
        /// cpu使用率
        /// </summary>
        private int CPUUsage
        {
            get { return m_cpu_usage; }
            set
            {
                m_cpu_usage = value;

                this.tsps_cpu.Text = "CPU 使用率： " + m_cpu_usage + "%";
                this.tsps_cpu.Image = img_memory.Images[value / 10];
            }
        }

        private float m_free_memory;
        /// <summary>
        /// 空闲内存
        /// </summary>
        private float FreeMemory
        {
            get { return m_free_memory; }
            set
            {
                m_free_memory = value;
                this.tsps_memory.Text ="空闲内存："+ m_free_memory + " Mb";
            }
        }

        /// <summary>
        /// 窗体加载链接信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmMain_Load(object sender, EventArgs e)
        {
           // this.tsps_connection.Text = GetInterneState();

            //m_crawler_mgr = new CrawlerManager();
            //Consts.CrawlerType t_crawler_type = Consts.CrawlerType.ALL;
            //m_crawler_mgr.SendMsg += new SendMsgEventHandler(ShowMsg);
            //m_crawler_mgr.CrawlerType = t_crawler_type;

            //Thread t_thd = new Thread(new ThreadStart(m_crawler_mgr.StartApp)); 
            //t_thd.Start();
        

            //tls_start.Enabled = false;
            //tls_stop.Enabled = true;
           
        }


        [DllImport("wininet")]
        public static extern int InternetGetConnectedState(ref int i_lpdw_flags, int i_dw_reserved);

        [DllImport("wininet")]
        public static extern int InternetAutodial(int i_dw_flags, int i_hwnd_parent);

        /// <summary>
        /// 获取网络链接信息
        /// </summary>
        /// <returns></returns>
        private  string GetInterneState()
        {
            string t_net_state = "";
            try
            {
                int t_state = 0;
           
                if (InternetGetConnectedState(ref t_state, 0) == 0)
                    return "网络无法链接到Internet";
                if ((t_state & 1) == 1)
                    t_net_state = "拨号链接正常";
                else if ((t_state & 2) == 2)
                    t_net_state = "网络链接正常";
                else if ((t_state & 4) == 4)
                    t_net_state = "代理链接正常";
                else if ((t_state & 8) == 8)
                    t_net_state = "路由器忙，不能分配链接";
                else if ((t_state & 0x10) == 0x10)
                    t_net_state = "远程链接受控";
                else if ((t_state & 0x20) == 0x20)
                    return "网线不正常";
                else if ((t_state & 0x40) == 0x40)
                    return "网络链接配置不正常";

                IPHostEntry he = Dns.Resolve(Dns.GetHostName());
                t_net_state += ",  机器IP: " + he.AddressList[0].ToString();
            }
            catch
            {
            }
            return t_net_state;
        }

        /// <summary>
        /// cpu和romery统计
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer_counter_Tick(object sender, EventArgs e)
        {
            FreeMemory =m_memory_counter.NextValue();

            CPUUsage = (int)m_cpu_counter.NextValue();
        }

        /// <summary>
        /// 系统配置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tlsm_config_Click(object sender, EventArgs e)
        {
            FrmSetting t_frm = new FrmSetting();
            t_frm.ShowDialog();
        }

        /// <summary>
        /// 站点管理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tlsm_site_Click(object sender, EventArgs e)
        {
            FrmBookSite t_frm = new FrmBookSite();
            t_frm.ShowDialog();
        }

        /// <summary>
        /// 开始
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tls_start_Click(object sender, EventArgs e)
        {
             m_crawler_mgr = new CrawlerManager();
            Consts.CrawlerType t_crawler_type = Consts.CrawlerType.ALL;
            m_crawler_mgr.SendMsg += new SendMsgEventHandler(ShowMsg);
            if (tls_comfrom.Text.ToString().Equals("新书收录"))
            {
                BookCrawManager t_book_mgr = new BookCrawManager();
                t_book_mgr.StartNewBook();
               
            }
            else if (tls_comfrom.Text.ToString().Equals("更新收录"))
            {
                t_crawler_type = Consts.CrawlerType.UpdateBook;
                m_crawler_mgr.CrawlerType = t_crawler_type;
                m_crawler_mgr.StartApp();

                tls_start.Enabled = false;
                tls_stop.Enabled = true;
            }
            else if (tls_comfrom.Text.ToString().Equals("重点收录"))
            {
                t_crawler_type = Consts.CrawlerType.ImportantBook;
                m_crawler_mgr.CrawlerType = t_crawler_type;
                m_crawler_mgr.StartApp();

                tls_start.Enabled = false;
                tls_stop.Enabled = true;
            }
          
        }

        /// <summary>
        /// 显示消息
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="i_msg_type"></param>
        private void ShowMsg(object sender, SendMsgEventArgs e)
        {
            if (e.MsgType == MsgType.Thread)
            {
                Monitor.Enter(this.listViewThreads);
                ShowThreadMsg(e.Msg);
                Monitor.Exit(this.listViewThreads);
            }

            //if (e.MsgType== MsgType.Request)
            //{
            //    Monitor.Enter(this.listViewRequests);
            //    ShowRequestMsg(e.Msg);
            //    Monitor.Exit(this.listViewRequests);
            //}
            //else if (e.MsgType == MsgType.Thread)
            //{
            //    Monitor.Enter(this.listViewThreads);
            //    ShowThreadMsg(e.Msg);
            //    Monitor.Exit(this.listViewThreads);
            //}
            //else if (e.MsgType == MsgType.Log)
            //{
            //    Monitor.Enter(this.listViewErrors);
            //    ShowErrorMsg(e.Msg);
            //    Monitor.Exit(this.listViewErrors);
            //}
        }

        /// <summary>
        /// 显示错误信息
        /// </summary>
        /// <param name="obj"></param>
        private void ShowErrorMsg(object obj)
        {
            LogMsg t_log_msg = obj as LogMsg;

            Monitor.Enter(this.listViewErrors);

            int t_error_count = this.listViewErrors.Items.Count;
            try
            {
                ListViewItem item = this.listViewErrors.Items.Insert(0, t_error_count.ToString());
                item.SubItems.AddRange(new String[] { t_log_msg.OcurTime.ToString(), t_log_msg.LogHeader, t_log_msg.LogBody });
               
            }
            catch (Exception ex)
            {
                LogHelper.Error("发生错误" + ex.ToString());
            }
            Monitor.Exit(this.listViewErrors);
        }

        /// <summary>
        /// 显示线程消息
        /// </summary>
        /// <param name="obj"></param>
        private void ShowThreadMsg(object obj)
        {
            ThreadMsg t_thread_msg = obj as ThreadMsg;

            Monitor.Enter(this.listViewThreads);

            int t_thread_index = 0;

            if (!int.TryParse(t_thread_msg.ThreadId, out t_thread_index))
                t_thread_index = 0;

            try
            {
                ListViewItem item = null;
                if (this.listViewThreads.Items.Count <= t_thread_index)
                {
                    item = this.listViewThreads.Items.Insert(this.listViewThreads.Items.Count, "");
                    item.SubItems.AddRange(new String[] {"","","","","" });
                }
                else
                {
                    item = this.listViewThreads.Items[t_thread_index];
                }

                item.SubItems[0].Text = t_thread_index.ToString();
                item.ImageIndex = t_thread_msg.ImageIndex;
                item.BackColor = t_thread_msg.BackColor;
                item.SubItems[1].Text = t_thread_msg.Action;
                item.ForeColor = t_thread_msg.ForeColor;
                item.SubItems[2].Text = t_thread_msg.Url;
                item.SubItems[4].Text = t_thread_msg.Percent;
                item.SubItems[3].Text = t_thread_msg.ByteCount;
            }
            catch (Exception ex)
            {
                LogHelper.Error("出现错误" + ex.ToString());
            }

            Monitor.Exit(this.listViewThreads);
        }

        /// <summary>
        /// 显示请求信息
        /// </summary>
        /// <param name="obj"></param>
        private void ShowRequestMsg(object obj)
        {
            RequestMsg t_request_msg = obj as RequestMsg;
            Monitor.Enter(this.listViewRequests);
			try
			{
				ListViewItem item = this.listViewRequests.Items.Insert(0, t_request_msg.OcurTime.ToString());
                item.SubItems.AddRange(new String[] { t_request_msg.RequestHeader, t_request_msg.RequestBody });
			
			}
			catch(Exception ex)
			{
                LogHelper.Error("出现错误" + ex.ToString());
			}
            Monitor.Exit(this.listViewRequests);
        }

        /// <summary>
        /// 请求信息详情
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void listViewRequests_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.listViewRequests.SelectedItems.Count == 0)
                return;
            ListViewItem item = this.listViewRequests.SelectedItems[0];
            if (item.SubItems.Count > 2)
                this.textBoxRequest.Text = item.SubItems[2].Text;
        }

        /// <summary>
        /// 错误详情
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void listViewErrors_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.listViewErrors.SelectedItems.Count == 0)
                return;
            ListViewItem item = this.listViewErrors.SelectedItems[0];
            if (item.SubItems.Count > 2)
                this.textBoxErrorDescription.Text = item.SubItems[3].Text;
        }

        /// <summary>
        /// 停止收录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tls_stop_Click(object sender, EventArgs e)
        {
            if (m_crawler_mgr != null)
            {
                m_crawler_mgr.StopApp();
            }
            tls_stop.Enabled = false;
            tls_start.Enabled = true;
        }

        /// <summary>
        /// 系统设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tls_setting_Click(object sender, EventArgs e)
        {
            FrmSetting t_frm = new FrmSetting();
            t_frm.ShowDialog();
        }

        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            Application.ExitThread();
            Environment.Exit(0);
            Process.GetCurrentProcess().Kill();
        }

        private void tlsm_baidu_Click(object sender, EventArgs e)
        {
            FrmTopBook t_frm = new FrmTopBook();
            t_frm.ShowDialog();
            
        }

        private void tlsp_test_Click(object sender, EventArgs e)
        {
            FrmTest t_frm = new FrmTest();

            t_frm.ShowDialog();

        }
       
        
    }
}
